package cn.fx.system.service.impl;


import cn.fx.basic.service.impl.BaseServiceImpl;
import cn.fx.system.domain.Role;
import cn.fx.system.mapper.RoleMapper;
import cn.fx.system.service.IRoleService;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.convert.RemoveIndexedData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
//查询的方法比较多，使用查询的事务配置
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 删除
     * @param rid
     */
    @Override
    @Transactional
    public void remove(long rid) {
        //删除中间表：t_role_permission
        roleMapper.removeRolePermission(rid);
        //删除中间表：t_role_menu
        roleMapper.removeRoleMenu(rid);
        //删除表：t_employee_role
        roleMapper.removeEmployeeRole(rid);
        //删除角色
        roleMapper.remove(rid);
    }

    /**
     * 添加
     */
    @Override
    @Transactional
    public void save(Role role) {
        //保存角色信息 三张表
        roleMapper.save(role);
        //操作相关信息，中间表信息: t_role_menu t_role_permission
        initRelationTable(role);
    }

    /**
     * 修改
     * @param role
     */
    @Transactional
    @Override
    public void update(Role role) {
        //修改
        roleMapper.update(role);
        //先删除中间表信息：t_role_permission
        roleMapper.removeRolePermission(role.getId());
        //先删除中间表信息：t_role_menu
        roleMapper.removeRoleMenu(role.getId());
        //再进行添加
        initRelationTable(role);
    }



    /**
     * 中间表保存方法
     * @param role
     */
    private void initRelationTable(Role role) {

        //角色分配权限
        if(role.getPermissions().size() > 0){
            roleMapper.saveRolePermisson(role.getId(), role.getPermissions());
        }
        //角色分配菜单
        if(role.getMenus().size() > 0) {
            roleMapper.saveRoleMenu(role.getId(),role.getMenus());
        }
    }

    /**
     * 批量删除重构
     */
    @Override
    @Transactional
    public void patchDel(List<Long> ids) {
        for (Long id : ids) {
            remove(id);
        }
    }
}
